import { useMemo, useRef, useState } from 'react';
import _ from 'lodash';
import { WithNormalRender } from '@/biz-components/hoc-form/with-normal';
import { onFieldInit, onFieldValueChange, onFormMount } from '@formily/core';
import { Button, Modal } from 'antd';
import ReactToPrint from 'react-to-print';
import BarPrint from './components/bar-print';
import { Form } from '@formily/core/esm/models';
import { archivesBoxPage } from './services';

import './print.less';
import './bar.less';

const FileBoxPrint = () => {
  const [printList, setPrintList] = useState<any[]>([]);
  const formRef = useRef<Form<any>>();
  const printContentRef = useRef<any>();

  const BillFormLayout = useMemo(() => {
    return WithNormalRender({});
  }, []);

  const handleAfterPrint = () => {
    Modal.confirm({
      title: '是否清空数据?',
      onOk: () => {
        setPrintList([]);
        formRef.current?.setValuesIn('fileBoxItems', undefined);
      },
    });
  };

  const searchFileBox = _.debounce(async (form: Form<any>, code: string) => {
    const { fileBoxItems } = form.values;
    const res: any = await archivesBoxPage({
      pageNo: 1,
      pageSize: 1,
      queryKeys: {
        code,
        pageCode: 'ArcvFileBox_L',
      },
    });

    if (res.success && !!res.result?.content?.length) {
      const target = res.result.content[0];

      const newFileBoxItems = fileBoxItems ? [...fileBoxItems, target] : [target];
      form.setValuesIn('fileBoxItems', newFileBoxItems);
      form.setValuesIn('code', undefined);
    }
  }, 500);

  return (
    <>
      <BillFormLayout
        anchor
        type="NORMAL"
        pageCode="ArcvFileBox_Print_C"
        events={{}}
        formConfigs={{
          effects: () => {
            onFormMount((form) => {
              formRef.current = form;
            });
            onFieldInit('fileBoxItems', (field, form) => {
              field.componentProps = {
                ...field.componentProps,
                headerRender: () => {
                  return (
                    <ReactToPrint
                      documentTitle="档案盒打印"
                      onAfterPrint={handleAfterPrint}
                      trigger={() => <Button type="primary">打印预览</Button>}
                      content={() => printContentRef.current}
                    />
                  );
                }
              };
            });
            onFieldInit('code', (field: any, form) => {
              field.componentProps.onInput = async (e: any) => {
                const { fileBoxItems } = form.values;
                const code = e.target.value;

                if (!code || fileBoxItems?.some((o: any) => o.code === code)) {
                  field.value = undefined;
                  return;
                }

                searchFileBox(form, code);
              };
            });
            onFieldValueChange('fileBoxItems', (field: any) => {
              setPrintList(field.value);
            });
          },
        }}
        filedConfig={{}}
        eventMap={{
          removeCb: (row: any, index: number) => {
            const { fileBoxItems } = formRef.current?.values || {};

            fileBoxItems.splice(index, 1);
            formRef.current?.setValuesIn('fileBoxItems', _.cloneDeep(fileBoxItems));

            return false;
          }
        }}
        needFooter={false}
      />
      <div style={{ display: 'none' }}>
        <div ref={(el) => (printContentRef.current = el)}>
          <BarPrint list={printList} />
        </div>
      </div>
    </>
  );
};

export default FileBoxPrint;
